Sort Colors
Given an array with n objects colored red, white or blue,
sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
题目大意:给定一个数组,数组只包含数字0,1,2,对数组排序,不能使用内置排序函数
题目难度:Medium
/**
* Created by gzdaijie on 16/5/30
* 桶排序,时间复杂度O(N)
*/
public class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length < 2) return;
int len = nums.length;
int[] count = new int[3];
int k = 0;
for (int i = 0; i < len; i++) count[nums[i]]++;
for (int i = 0; i < count[0]; i++) nums[k++] = 0;
for (int i = 0; i < count[1]; i++) nums[k++] = 1;
for (int i = 0; i < count[2]; i++) nums[k++] = 2;
}
}